/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufg.inf.viwvc;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author Jose Fernando Tolentino
 */
public class VI_WVC_2012Servlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 624952844530332114L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String caminho = req.getPathInfo();
		if (caminho.endsWith(".page")) {
			serveJsp("paginas", caminho.substring(0, caminho.length() - 5),
					req, resp);
		} else if (caminho.endsWith(".news")) {
			serveJsp("novidades", caminho.substring(0, caminho.length() - 5),
					req, resp);
		} else {
			executaComando(caminho.substring(1), req, resp);
		}
	}

	private void executaComando(String cmd, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		Sessao sessao = Sessao.init(req);
		Controler ctrl = null;
		try {

			@SuppressWarnings("unchecked")
			Class<Controler> clazz = (Class<Controler>) Class
					.forName("viwvc.controller.cmds." + cmd);
			ctrl = clazz.newInstance();
			String rd = ctrl.execute(sessao, req);
			resp.sendRedirect(rd);

		} catch (Exception e) {
			throw new ServletException(e);
		} finally {
			sessao.closeDatabase();
		}
	}

	protected void serveJsp(String dir, String nome, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");

		PrintWriter out = resp.getWriter();

		out.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

		out.append("<html>");
		out.append("<head>");
		out.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
		out.append("<title>VIII WVC 2012 - UFG</title>");
		req.getRequestDispatcher("/jsp/segmentos/includes.jsp").include(req,
				resp);
		out.append("</head>");

		out.append("<body>");

		req.getRequestDispatcher("/jsp/segmentos/cabecalho.jsp").include(req,
				resp);

		out.append("<section class=\"row\" id=\"styled\">");
		out.append("<div class=\"col col_11\">");
		req.getRequestDispatcher("/jsp/" + dir + nome+".jsp").include(req, resp);
		out.append("</div>");
		out.append("<div class=\"col col_5\">");
		req.getRequestDispatcher("/jsp/segmentos/barra.jsp").include(req, resp);
		out.append("</div>");
		out.append("</section>");

		req.getRequestDispatcher("/jsp/segmentos/rodape.jsp")
				.include(req, resp);

		out.append("</body></html>");

	}
}
